package muilt;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import com.FDaasApplicationSpring;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;


@RunWith(SpringRunner.class)
@SpringBootTest(classes={FDaasApplicationSpring.class}) // 指定spring-boot的启动类
public class restTemp{
	
	@Autowired
	private RestTemplate restTemplate;
	
	//private static final MediaType ME_JSON = MediaType.parse("application/json; charset=utf-8");
	/*private static OkHttpClient client = new OkHttpClient.Builder()
			.connectTimeout(10, TimeUnit.DAYS)
			.writeTimeout(10, TimeUnit.DAYS)
			.readTimeout(10, TimeUnit.DAYS)
			.build();*/ 
	List<String> cookies;
	private boolean noLogin = true;
	private String userName = "admin";
	private String passWord = "654321";
	private int tryLoginTimes = 10;
	private long lastBeatTime = 0; 
    //固定执行时间，时间单位为毫秒,读者可自行设定，不得小于等于0
    private static Integer cacheTime = 600000; //10分钟
    //开始后延迟时间，时间单位为毫秒,读者可自行设定，不得小于等于0
    private static Integer delay = 1000;
    private String host = "http://localhost/";
	private String loingUrl = host + "api/Admin/Login";
	private String buildingUrl = host + "api/Building/GetBuildingInfo?&moiid=%s";
	private String buildingRy =  host + "api/Building/GetBuildingRy?&moiId=%s";
	private String getAll = host + "api/Building/GetAll?&minX=%s&minY=%s&maxX=%s&maxY=%s";
	private String refreshUrl = buildingUrl + "1165";
	
	@Test
	public void test(){
		System.out.println(GetBuildingInfo("1165"));
		System.out.println(GetBuildingRy("1165"));
		System.out.println(GetAll("13722830.382734943","4070785.3280186914","13723429.245649494","4071290.524180713"));
	}
	
	public String GetAll(String minX,String minY,String maxX,String maxY){ 
		try {
			if(noLogin){
				relogin(tryLoginTimes);
			}
		    return get(String.format(getAll, minX,minY,maxX,maxY));
		} catch (Exception e) {
			e.printStackTrace(); 
			return "FAIL";
		} finally{
			resfreshBeaTime();
		}
	} 
	
	public String GetBuildingInfo(String moiid){
		 
		try { 
			if(noLogin){
				relogin(tryLoginTimes);
			}
		    return get(String.format(buildingUrl,moiid));
		} catch (Exception e) {
			e.printStackTrace();
			 
			return "FAIL";
		} finally{
			resfreshBeaTime();
		}
	} 

	public String GetBuildingRy(String moiid){
		 
		try {
			if(noLogin){
				relogin(tryLoginTimes);
			}
			return get(String.format(buildingRy,moiid));
		} catch (Exception e) {
			e.printStackTrace(); 
			return "FAIL";
		} finally{
			resfreshBeaTime();
		}
	}
	
    private void heartBeat(){
    	 Timer timer = new Timer();
         timer.schedule(new TimerTask() {
        	 @Override
        	 public void run(){
        		 refreshSession();
           	 }
         }, delay, cacheTime);
    } 
	
    /**
     * 刷新服务器的session时间
     */
    private void refreshSession(){
    	try { 
    		if(System.currentTimeMillis() - lastBeatTime < cacheTime){
    			return;
    		}
    		if(noLogin){
    			relogin(tryLoginTimes);
    		}
    		if(!noLogin){ 
    			get(refreshUrl); 
    		}
    		resfreshBeaTime();
		} catch (Exception e) {
			e.printStackTrace();
		 
		}
    } 
    /**
     * 刷新心跳时间
     */
    private void resfreshBeaTime(){
    	lastBeatTime = System.currentTimeMillis();
    }
	/**
	 * 如果登录失败进行 重复登录count次
	 * @throws InterruptedException 
	 */
	private boolean relogin(int count) throws InterruptedException{ 
		count--;
		if(doLoing()){
			return true;
		}else if(count >= 0){
			Thread.sleep(1000);
            return relogin(count);
		}else{
			return false;
		}
    }
	/**
	 * 真实的登录方法 
	 */
	public boolean doLoing(){ 
        HttpHeaders header = new HttpHeaders(); 
        header.setContentType(MediaType.APPLICATION_JSON_UTF8); 
        HttpEntity<ImmutableMap<String, String>> request = new HttpEntity<>(
        		ImmutableMap.of("userName", userName, "userPassword", passWord), header);
        try{
        	ResponseEntity<String> response = restTemplate.postForEntity(loingUrl, request, String.class);       //地址替换为自己的
        	noLogin = false;
			cookies = response.getHeaders().get("Set-Cookie");
			return true;
		} catch (Exception e) {
			return false;
		} 
	}
 
	/**
	 * get请求
	 * @param url
	 * @return
	 */
	private String get(String url){
		HttpHeaders headers = new HttpHeaders(); 
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.set("Cookie", Joiner.on(",").skipNulls().join(cookies));  
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); 
        return restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
	}
	
} 